import { Vector2 } from "../vector";  
import { Engine } from "../engine";
import { CameraEffect } from "./camera-effect";  
import { lerp } from "../utils";  

  
export interface CameraPathPoint {  
  pos: Vector2;  
  time: number; // 到达此点的时间（0-1）  
}  
  
export class PathEffect extends CameraEffect {  
  private path: CameraPathPoint[];  
  private loop: boolean;  
  
  constructor(engine: Engine, path: CameraPathPoint[], loop: boolean = false) {  
    super(engine);  
    this.path = path.sort((a, b) => a.time - b.time);  
    this.loop = loop;  
  }  
  
  apply(basePos: Vector2): Vector2 {  
    if (!this.isActive || this.path.length < 2) return basePos;  
  
    let progress = this.progress;  
    if (this.loop && this.isFinished) {  
      progress = (this.engine.time_ - this.startTime) % this.duration / this.duration;  
    }  
  
    // 找到当前进度对应的路径段  
    let currentPoint = this.path[0];  
    let nextPoint = this.path[1];  
  
    for (let i = 0; i < this.path.length - 1; i++) {  
      if (progress >= this.path[i].time && progress <= this.path[i + 1].time) {  
        currentPoint = this.path[i];  
        nextPoint = this.path[i + 1];  
        break;  
      }  
    }  
  
    // 在两点间插值  
    const segmentProgress = (progress - currentPoint.time) / (nextPoint.time - currentPoint.time);  
    const interpolatedPos = new Vector2(  
      lerp(currentPoint.pos.x, nextPoint.pos.x, segmentProgress),  
      lerp(currentPoint.pos.y, nextPoint.pos.y, segmentProgress)  
    );  
  
    return interpolatedPos;  
  }  
}